<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    .modal {
      position: fixed;
      width: 200px;
      height: 160px;
      line-height: 200px;
      text-align: center;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      background-color: #eee;
    }
  </style>
  <body>
    <button id="display">显示</button>
    <button id="hidden">隐藏</button>
    <script>
      const Modal = (function () {
        let instance;
        return function () {
          if (!instance) {
            instance = document.createElement("div");
            instance.className = "modal";
            instance.innerHTML = "登陆对话框";
          }
          return instance;
        };
      })();

      document.querySelector("#display").addEventListener(
        "click",
        function () {
          const modal = Modal();
          document.body.appendChild(modal);
        },
        false
      );

      // 能够精准删除掉对话框元素，因为使用 Modal() 得到的元素是添加到页面的元素本体（单例）。
      document.querySelector("#hidden").addEventListener(
        "click",
        function () {
          const modal = Modal();
          document.body.removeChild(modal);
        },
        false
      );
    </script>
  </body>
</html>
